package com.block.product.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.enums.ChargeTypeEnum;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.db.entity.MemberBaseInfo;
import com.block.db.entity.ProductBaseInfo;
import com.block.db.entity.ProductOnlieInfo;
import com.block.db.entity.ProductUnionResultInfo;
import com.block.db.mapper.MemberBaseInfoMapper;
import com.block.db.mapper.ProductUnionResultInfoMapper;
import com.block.product.enums.UniStatusEnum;
import com.block.product.factory.UnionLoginFactory;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class ProductUnionLoginService implements IProductUnionLoginService {

    private static final Logger log = LogFactory.getProductLog();

    @Resource
    ProductUnionResultInfoMapper productUnionResultInfoMapper;
    @Autowired
    IProductBaseInfoService productBaseInfoService;
    @Resource
    MemberBaseInfoMapper memberBaseInfoMapper;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IProductProfitUvInfoService productProfitUvInfoService;
    @Autowired
    IProductOnlieInfoService productOnlieInfoService;
    @Autowired
    IProductProfitInfoService productProfitInfoService;
    @Autowired
    IProductUnionResultInfoService productUnionResultInfoService;

    /**
     * 获取联登产品信息
     * 1.是否可以显示
     */
    @Override
    public UnionLoginResult getUnionProductShowInfo(ProductBaseInfo productBaseInfo, Long uid) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        ProductUnionResultInfo productUnionResultInfo = productUnionResultInfoMapper.getEntityByProductIdAndUid(String.valueOf(productBaseInfo.getId()), uid);
        if (ObjectUtil.isEmpty(productUnionResultInfo)) {
            // 为空，进行联登撞库
            String redisKey = StrUtil.format("{}-{}", productBaseInfo, uid);
            productUnionResultInfo = productUnionResultInfoService.getUnionProductCheckResult(productBaseInfo, uid, redisKey);
            if (ObjectUtil.isEmpty(productUnionResultInfo)) {
                loginResult.setMessage("撞库结果为空");
                return loginResult;
            }
        }

        // 不为空，判断是否可以返回产品链接
        if (StrUtil.equals(productUnionResultInfo.getStatus(), UniStatusEnum.WAIT_LOGIN.getValue())) {
            loginResult.setSuccess(true);
            return loginResult;
        }
        if (StrUtil.equals(productUnionResultInfo.getStatus(), UniStatusEnum.SUCCESS.getValue())) {
            LocalDateTime expireTime = productUnionResultInfo.getExpireTime();
            LocalDateTime nowTime = LocalDateTime.now();
            if (nowTime.isBefore(expireTime)){
                loginResult.setSuccess(true);
                String loginUrl = productUnionResultInfo.getLoginUrl();
                if (StrUtil.isEmpty(loginUrl)){
                    loginResult.setLoginUrl("");
                }else{
                    loginResult.setLoginUrl(loginUrl);
                }
            }else{
                loginResult.setMessage("联登成功，展示时间超时，不展示");
            }
            return loginResult;
        }

        loginResult.setMessage("记录状态错误，不展示");
        return loginResult;
    }


    private ProdApiInfoParam getProdApiInfoParam(ProductBaseInfo productBaseInfo) {
        ProdApiInfoParam prodApiInfoParam = new ProdApiInfoParam();
        prodApiInfoParam.setApiCode(productBaseInfo.getApiCode());
        prodApiInfoParam.setApiKey(productBaseInfo.getApiKey());
        prodApiInfoParam.setApiSecret(productBaseInfo.getApiSecret());
        prodApiInfoParam.setApiPubKey(productBaseInfo.getPubKey());
        prodApiInfoParam.setApiPriKey(productBaseInfo.getPriKey());
        prodApiInfoParam.setCheckUrl(productBaseInfo.getCheckUrl());
        prodApiInfoParam.setLoginUrl(productBaseInfo.getLoginUrl());
        return prodApiInfoParam;
    }

    /**
     * 获取联登结果
     * @param resultInfoId
     * @param uid
     * @param productId
     * @return
     */
    @Override
    @Transactional
    public ProductUnionResultInfo getUnionProductLoginResult(Integer resultInfoId, Long uid, Integer productId) {
        try {
            MemberBaseInfo memberBaseInfo = memberBaseInfoMapper.selectById(uid);

            ProductUnionResultInfo productUnionResultInfo = productUnionResultInfoMapper.getEntityByIdLock(resultInfoId);
            ProductBaseInfo productBaseInfo = productBaseInfoService.getProductInfoById(productId);

            // 进行撞库操作
            UniLoginDTO uniLoginDTO = new UniLoginDTO();
            uniLoginDTO.setMobile(memberBaseInfo.getMobile());

            ProdApiInfoParam prodApiInfoParam = this.getProdApiInfoParam(productBaseInfo);

            UnionLoginResult checkResult = UnionLoginFactory.getService(productBaseInfo.getFactoryType()).loginUser(uniLoginDTO, prodApiInfoParam);
            log.info("【产品联登登陆】撞库操作【checkResult】{}【UniLoginDTO】{}【productId】{}", JSON.toJSONString(checkResult), JSON.toJSONString(uniLoginDTO), productBaseInfo.getId());

            ProductUnionResultInfo updateEntity = new ProductUnionResultInfo();
            updateEntity.setId(productUnionResultInfo.getId());
            updateEntity.setCode(checkResult.getCode());
            updateEntity.setMessage(checkResult.getMessage());
            updateEntity.setResultInfo(checkResult.getResultInfo());
            updateEntity.setParamInfo(checkResult.getParamInfo());
            // 联登产品展示的有效期为1天
            updateEntity.setExpireTime(LocalDateTime.now().plusDays(1L));

            if (checkResult.isSuccess()) {
                updateEntity.setStatus(UniStatusEnum.SUCCESS.getValue());
                updateEntity.setLoginUrl(checkResult.getLoginUrl());
            } else {
                updateEntity.setStatus(UniStatusEnum.FAILED.getValue());
            }
            int i = productUnionResultInfoMapper.updateById(updateEntity);
            log.info("【产品联登登陆】更新登陆结果【i】{}【uid】{}【productId】{}", 1, uid, productBaseInfo.getId());
            if (i > 0) {

                if (ObjectUtil.equals(productBaseInfo.getChargeType(), ChargeTypeEnum.UNION.getValue())){
                    // 统计uv或者注册产品的点击
                    // 2.统计
                    ProductOnlieInfo productOnlieInfo = productOnlieInfoService.getById(productId);
                    productProfitInfoService.recordProductProfitInfo(productId, productOnlieInfo, productBaseInfo, LocalDate.now().toString(), memberBaseInfo.getChannelCode());
                }

                return productUnionResultInfoMapper.selectById(productUnionResultInfo.getId());
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            String message = StrUtil.format("【resultInfoId】{}【uid】{}【productId】{}", resultInfoId, uid, productId);
            notifyExceptionService.notifyNoticeInfo("UNION_PRODUCT_LOGIN", "联登登陆异常", message, exception);
        }
        return null;
    }

}
